package com.lcredu.web;
/**
 * @author 黎长容
 * @date 2025-07-06 11:22
 */

import com.lcredu.entity.Furn;
import com.lcredu.entity.Page;
import com.lcredu.service.FurnService;
import com.lcredu.service.impl.FurnServiceImpl;
import com.lcredu.utils.DataUtils;
import com.lcredu.utils.DefaultMsg;
import com.lcredu.utils.WebUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

@WebServlet(name = "FurnServlet", urlPatterns = "/manage/FurnServlet")
public class FurnServlet extends BasicServlet {
    private FurnService furnService = new FurnServiceImpl();


    /*
        1.如果表单提交方式为enctype="multipart/form-data" 则不能直接通过 request.getParameter("name");获取
     */
    protected void updateFurn(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = DataUtils.parserInt(request.getParameter("id"), 0);
        //获取这个id带过来的furn对象
        Furn furn = furnService.getFurn(id);


        //1.判断是不是文件表单
        if (ServletFileUpload.isMultipartContent(request)) {
            //2.创建数据上传的工具对象
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //3.创建一个解析上传数据的工具对象
            ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
            //4.使用解析上传数据的工具对象

            try {
                List<FileItem> furnList = fileUpload.parseRequest(request);
                for (FileItem fileItem : furnList) {
//                    System.out.println(fileItem);
                    if (fileItem.isFormField()) {
                        //开始填充
                        if ("name".equals(fileItem.getFieldName())) {
                            furn.setName(fileItem.getString("utf-8"));
                        } else if ("maker".equals(fileItem.getFieldName())) {
                            furn.setMaker(fileItem.getString("utf-8"));
                        } else if ("price".equals(fileItem.getFieldName())) {
                            furn.setPrice(new BigDecimal(fileItem.getString("utf-8")));
                        } else if ("sales".equals(fileItem.getFieldName())) {
                            furn.setSales(Integer.parseInt(fileItem.getString("utf-8")));
                        } else if ("stock".equals(fileItem.getFieldName())) {
                            furn.setStock(Integer.parseInt(fileItem.getString("utf-8")));
                        }
                    } else {
                        //文件表单:图片
                        String name = fileItem.getName();
                        String oldImage = furn.getimgPath();

                        if (!name.equals("")) {

                            name = UUID.randomUUID().toString() + "_" + name;

                            //3.把东西放进去
                            String fileRealPath = WebUtils.fileUpload(request);
                            fileItem.write(new File(fileRealPath + "/" + name));
                            System.out.println("fileRealPath=" + fileRealPath);
                            //4.传入furn
//                            furn.setimgPath(DefaultMsg.DEFAULT_FILEPATH.getFilePath() + "/" + name);

                            String imgPath = DefaultMsg.DEFAULT_FILEPATH.getFilePath() + "/" + WebUtils.setDir() + "/" + name;
                            furn.setimgPath(imgPath);

                            //删除原来的图片
//                            fileRealPath
                            //这个方法可以获取项目实际目录,用来删除之前多余的图片非常有用!!!
                            String realPath = request.getServletContext().getRealPath(oldImage);
                            System.out.println("fff=" + realPath );
                            File file = new File(realPath);
                            System.out.println("存在吗?" + file.exists());
                            if (file.isFile() || file.exists()) {
                                file.delete();
                            }
                        }
                    }
                }
            } catch (FileUploadException e) {
                throw new RuntimeException(e);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        furnService.updateFurn(furn);

        request.getRequestDispatcher("/views/manage/checkout.jsp").forward(request, response);
    }

    /**
     * 这里使用basicServlet可以进行反射调用
     * 黎长容知识点3: 设置标签页
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("list()方法被调用...");
        List<Furn> furns = furnService.getFurns();
        request.setAttribute("furns", furns);
        //请求转发
        request.getRequestDispatcher("/views/manage/furn_manage.jsp").forward(request, response);
    }


    protected void furnAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        String name = request.getParameter("name");
//        String maker = request.getParameter("maker");
//        String price = request.getParameter("price");
//        String sales = request.getParameter("sales");
//        String stock = request.getParameter("stock");
        /**
         * 黎长容知识6.参数验证
         * 1.前端参数验证
         * 正则表达式
         * 2.后端参数验证
         * 后端正则表达式
         * try-catch异常捕获
         * 3.JSR303--springMVC在学,现在先用异常捕获
         */
//        Furn furn = null;
//        try {
//            furn = new Furn(null, name, DefaultMsg.DEFAULT_IMG_PATH.getImgPath(), maker, new BigDecimal(price), Integer.parseInt(sales), Integer.parseInt(stock));
//        } catch (NumberFormatException e) {
//            request.setAttribute("errorMsg","参数填写错误");
//            request.getRequestDispatcher("/views/furn/furn_add.jsp").forward(request,response);
//            
//        }


        /**
         * 黎长容知识7:自动封装javaBean
         * 其中的图片地址可以在实体类进行修改
         * 如果没有传入就赋值默认值
         * 如果传入了就按传入的来
         */
        Furn furn = new Furn();
        DataUtils.getBeanFromMap(request.getParameterMap(), furn);

//        try {
//            BeanUtils.populate(furn,request.getParameterMap());
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }


        if (furnService.add(furn) > 0) {
            //转发
//            System.out.println("增加成功...");
//            request.getRequestDispatcher("/manage/FurnServlet?action=list").forward(request,response);
            //黎长容知识5
            //用户刷新页面时会造成数据重复提交
            //解决方案:重定向
//            response.sendRedirect(request.getContextPath() + "/manage/FurnServlet?action=list");
            response.sendRedirect(request.getContextPath() + "/manage/FurnServlet?action=page&pageNum=" + request.getParameter("pageNum "));
        } else {
            //增加失败...
            System.out.println("增加失败...");
            request.getRequestDispatcher("/views/manage/furn_add.jsp").forward(request, response);
        }
    }


    protected void deleteById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        int delId = DataUtils.parserInt(id, 0);
        if (furnService.deleteById(delId) > 0) {
            //删除成功,跳转商品列表页
            //考虑分页
//            response.sendRedirect(request.getContextPath() + "/manage/FurnServlet?action=list");
            response.sendRedirect(request.getContextPath() + "/manage/FurnServlet?action=page&pageNum=" + request.getParameter("pageNum"));
        } else {
            //删除失败
            request.getRequestDispatcher("/furn_manage.jsp").forward(request, response);
        }
    }

    protected void queryFurnById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //第一步:找出这个id的所有属性,进行回显
        String id = request.getParameter("id");
        int furnId = Integer.parseInt(id);
        Furn furn = furnService.getFurn(furnId);
        if (furn != null) {
            //如果找到了,跳转到增加页面
            request.setAttribute("furn", furn);
            request.getRequestDispatcher("/views/furn/furn_update.jsp").forward(request, response);
        } else {
            //没找到
            System.out.println("暂未找到");
            request.getRequestDispatcher("/views/furn/furn_add.jsp").forward(request, response);
        }
    }

//    protected void updateFurn(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        //这里接收传过来的数据进行修改操作
//        Furn furn = new Furn();
//        DataUtils.getBeanFromMap(request.getParameterMap(), furn);
//        System.out.println(furn);
//        Boolean isUpdate = furnService.updateFurn(furn);
//        if (isUpdate) {
//            //修改成功进行页面跳转,重新获取列表数据
////            response.sendRedirect(request.getContextPath() + "/manage/FurnServlet?action=list");
//            //修改为分页
//            response.sendRedirect(request.getContextPath() + "/manage/FurnServlet?action=page&pageNum=" + request.getParameter("pageNum"));
//        } else {
//            System.out.println("修改失败");
//            response.sendRedirect(request.getContextPath() + "/views/furn/furn_update.jsp");
//        }
//
//    }

    protected void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int pageNum = DataUtils.parserInt(request.getParameter("pageNum"), 1);
        int pageSize = DataUtils.parserInt(request.getParameter("pageSize"), DefaultMsg.DEFAULT_PAGE_SIZE.getPageSize());

        //调用方法
        Page<Furn> page = furnService.getPage(pageNum, pageSize);
        //将page放入域中
        request.setAttribute("page", page);
        request.getRequestDispatcher("/views/manage/furn_manage.jsp").forward(request, response);

    }
}